import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card, Row, Col, Select, Button,
} from 'antd';

import { DetailInfoItem } from './data';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
interface DataDockSaveProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: DetailInfoItem;
  loading: boolean;
  INITINFO: any;
  location: { query: any };
}

interface DataDockSaveState {
  type: number;
  perLogisType: number | string;
  formValues: any;
}

@connect(({
  cainiaoDataDockAdd: { dataInfo },
  common: { INITINFO },
}: any) => ({
  dataInfo,
  INITINFO,
}))
class DataDockSaveInfoElem extends Component<DataDockSaveProps, DataDockSaveState> {
  state: DataDockSaveState = {
    type: 1,
    perLogisType: '',
    formValues: {},
  };

  static getDerivedStateFromProps(nextProps: DataDockSaveProps, preState: DataDockSaveState) {
    const { dataInfo } = nextProps;
    const { perLogisType } = preState;
    if ((dataInfo.pcId && perLogisType !== dataInfo.type)) {
      return {
        companyID: dataInfo.pcId,
        type: dataInfo.type,
        perLogisType: dataInfo.type,
      };
    }
    return null;
  }

  componentDidMount() {
    const {
      location: { query: { id } },
    } = this.props;
    if (id) this.fetchDetailInfo(id);

    this.fetchAction('common/fetchLogisList');
  }

  componentDidUpdate(prevProps: any) {
    const {
      location: { query: { id } },
    } = this.props;
    if (id && id !== prevProps.location.query.id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'cainiaoDataDockAdd/fetch',
      payload: { id },
    });
  };

  handleSelectLog = (id: number, e: any) => {
    const { formValues } = this.state;
    const params = {
      logisId: id,
      logisCode: e.key,
      logisName: e.props.children,
    };
    this.setState({ formValues: { ...formValues, ...params } });
  };

  handleSubmit = () => {
    const { formValues } = this.state;
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { logis } = values;
      const params = {
        ...values,
        ...formValues,
        logisId: logis ? logis.key : '',
        logisName: logis ? logis.label : '',
      };

      delete params.logis;

      const { location: { query: { id } } } = this.props;

      if (id) params.id = id;
      this.fetchAction('saveOrUpdatePartner', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `cainiaoDataDockAdd/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const { type } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList },
      location: { query },
    }: any = this.props;

    return (
      <Fragment>
        <PageHeader />
        <Card bordered={false}>
          <Form hideRequiredMark className="tableListForm">
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　类型" colon={false}>
                  {getFieldDecorator('type', {
                    initialValue: type,
                    rules: [{ required: true, message: '请选择类型' }],
                  })(
                    <Select allowClear placeholder="请选择">
                      <Option value={1}>物流中心</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="物流中心" colon={false}>
                  {getFieldDecorator('logis', {
                    initialValue: dataInfo.logisId && {
                      key: dataInfo.logisId,
                      label: dataInfo.logisName,
                    },
                    rules: [{ required: true, message: '请选择物流中心' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      labelInValue
                      disabled={Boolean(query.id)}
                      onChange={this.handleSelectLog}
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="　　状态" colon={false}>
                  {getFieldDecorator('status', {
                    initialValue: dataInfo.status || 1,
                    rules: [{ required: true, message: '请选择状态' }],
                  })(
                    <Select placeholder="请输入">
                      <Option value={1}>有效</Option>
                      <Option value={0}>无效</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={12} sm={24}>
                <Button
                  type="primary"
                  onClick={this.handleSubmit}
                >
                  保存
                </Button>
                <Button
                  ghost
                  type="primary"
                  className="marginL16"
                  onClick={() => router.goBack()}
                >
                  取消
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<DataDockSaveProps>()(DataDockSaveInfoElem);
